package com.bookmarket.view;

import com.alibaba.druid.util.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class ExcelView extends AbstractXlsView {
    //定义一个文件名
    private String fileName=null;
    //定义一个接口
    private ExcelExportService excelExportService=null;

    //当ExcelView被new 的时候就执行下面的方法进行判断了
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {

        if(excelExportService==null){
            throw new RuntimeException("导出服务接口不能为空");
        }

        //StringUtils.isEmpty() 常用方法，判断字符串是否为空。
        if(!StringUtils.isEmpty(fileName)){
            //进行字符转换
            String reqCharset=request.getCharacterEncoding();
            reqCharset=reqCharset==null?"UTF-8":reqCharset;//利用三元运算符判断编码方式
            fileName=new String(fileName.getBytes(reqCharset),"ISO8859-1");
            //设置下载的文件名（固定写法）
            response.setHeader("Content-disposition","attacment;filename="+fileName);
           // System.out.println(fileName);
        }
        //回调接口方法，使用自定义生成文档
        excelExportService.makeWorkBook(model,workbook);
    }




    //两个构造方法
    public ExcelView(ExcelExportService excelExportService) {
        this.excelExportService = excelExportService;
    }


    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public ExcelExportService getExcelExportService() {
        return excelExportService;
    }

    public void setExcelExportService(ExcelExportService excelExportService) {
        this.excelExportService = excelExportService;
    }
}